"use client";

import { useCreateWorkspace, useTaskRun } from "@/service/align";
import { useInputLoadStore } from "@/store/input";
import { useCountStore } from "@/store/task";
import AccountCircle from "@mui/icons-material/AccountCircle";
import NavigationIcon from "@mui/icons-material/Navigation";
import LoadingButton from "@mui/lab/LoadingButton";
import { Box, Button, Typography } from "@mui/material";
import Paper from "@mui/material/Paper";
import TextField from "@mui/material/TextField";
import { styled } from "@mui/material/styles";
import { message } from "antd";
import { useRouter } from "next/navigation";

const Item = styled(Paper)(({ theme }) => ({
  backgroundColor: theme.palette.mode === "dark" ? "#1A2027" : "#fff",
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: "center",
  color: theme.palette.text.secondary,
  flexGrow: 1,
  transition: theme.transitions.create(["height"], {
    duration: 1000,
  }),
}));

export default function StepThree(props: any) {
  const { email, setEmail, file_ids, pdb_ids, filter_options, clean } =
    useCountStore();
  const router = useRouter();
  const { clean: cleanInputStore } = useInputLoadStore();

  const { mutateAsync: createWorkspace, isPending: createWorkspaceLoading } =
    useCreateWorkspace();

  const { mutateAsync: taskRun, isPending: taskRunLoading } = useTaskRun();

  const handleRun = async () => {
    let workDir = "";

    if (!email) {
      message.warning("Please enter your email address");
      return;
    }

    if (
      filter_options.is_filter &&
      !filter_options.bacterial_filter.length &&
      !filter_options.phage_filter.length &&
      !filter_options.prophage_filter.length
    ) {
      message.warning("Please select a filter");
      return;
    }

    if (!filter_options.is_filter && !filter_options.options.length) {
      message.warning("Please select a filter");
      return;
    }

    try {
      const createWorkspaceResponse: any = await createWorkspace({
        file_ids: [...file_ids],
        pdb_ids: [...pdb_ids],
        filter_options: {
          ...filter_options,
        },
        email: email,
      });
      workDir = createWorkspaceResponse.work_dir;
      message.success("Workspace created successfully");
    } catch (error: any) {
      if (error?.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error("Failed to create workspace");
      }
    }

    if (!workDir) {
      message.info("Workspace not found");
    }

    try {
      await taskRun({
        workspace_dir: workDir,
        email: email,
      });
      props.setOpen(true);
      router.push("task");
    } catch (error: any) {
      if (error?.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error("Failed to create Run");
      }
    } finally {
      clean();
      cleanInputStore();
    }
  };

  return (
    <Item
      sx={{
        height: "520px",
        position: "relative",
      }}
    >
      <Typography
        sx={{ flex: "1 1 100%", marginTop: "1rem", marginBottom: "1rem" }}
        variant="h6"
        component="div"
      >
        Commence{" "}
        <Box component="span" sx={{ color: "primary.main" }}>
          Execution
        </Box>
      </Typography>

      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          marginTop: "7rem",
        }}
      >
        <Box
          sx={{
            display: "flex",
            alignItems: "flex-end",
            justifyContent: "center",
            width: "400px",
          }}
        >
          <AccountCircle
            sx={{ color: "primary.main", fontSize: "32px", mr: 1, my: 0.5 }}
          />
          <TextField
            id="input-with-sx"
            label="Email Address"
            variant="standard"
            size="medium"
            value={email}
            onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
              setEmail(event.target.value.trim());
            }}
            fullWidth
          />
        </Box>
      </Box>

      <Box
        sx={{
          marginTop: "2rem",
        }}
      >
        <Button
          variant="text"
          sx={{
            padding: "0.5rem 2rem",
            textTransform: "none",

            marginRight: "1rem",
          }}
          onClick={() => props.handleLastStep(2)}
        >
          Last Step
        </Button>
        <LoadingButton
          loading={createWorkspaceLoading || taskRunLoading}
          color="primary"
          variant="contained"
          onClick={() => handleRun()}
          sx={{ textTransform: "none" }}
        >
          <NavigationIcon sx={{ mr: 1 }} />
          Start Run
        </LoadingButton>
      </Box>
    </Item>
  );
}
